package com.yue.collection.weather.service.impl;

import com.yue.collection.weather.constant.Constant;
import com.yue.collection.weather.service.IWeatherDataConllectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 天气数据采集实现类
 *
 * @author yuelinbo
 * @date 2018年07月25日 11:10
 * Copyright:2018-版权所有
 */
@Service
public class WeatherDataCollectionServiceImpl implements IWeatherDataConllectionService {

    private final static Logger logger = LoggerFactory.getLogger(WeatherDataCollectionServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void syncDataByCityId(String cityId) {

        String url = Constant.WEATHER_ID_URL + cityId;
        saveWeatherData(url);
    }

    private void saveWeatherData(String url) {

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String strBody = null;

        ResponseEntity<String> respString = restTemplate.getForEntity(url, String.class);
        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }
        //写入缓存
        ops.set(url, strBody, Constant.TIME_OUT, TimeUnit.SECONDS);
    }


}
